<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px"
      class="demo-form-inline">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="活动编号">
            <el-input v-model="queryParams.id" placeholder="请输入活动编号" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="活动名称">
            <el-input v-model="queryParams.name" placeholder="请输入活动名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="优惠券">
            <el-select v-model="queryParams.typeId" placeholder="请选择优惠券类型" clearable @change="handleQuery">
              <el-option v-for="item in couponTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发放状态">
            <el-select v-model="queryParams.status" placeholder="请选择发放状态" clearable @change="handleQuery">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mb8">
        <el-col :span="24" class="text-right">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['activity:activity:add']">新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column label="活动编号" width="200" align="center" maxlength="19" prop="id" />
      <el-table-column label="活动名称" width="220" align="center" prop="name" />
      <el-table-column label="优惠券类型" width="150" align="center" prop="typeId" />
      <el-table-column label="满额限制（元）" width="150" align="center" prop="discountAmount" />
      <el-table-column label="折扣金额（元）" width="150" align="center" prop="discountRate" />
      <el-table-column label="使用范围" width="150" align="center" prop="scopeUse" />
      <el-table-column label="适用对象" align="center" prop="applicableObjects" width="150" />
      <el-table-column label="发放时间" align="center" prop="distributeStartTime" width="180">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.distributeStartTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="distributeEndTime" width="180">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.distributeEndTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用期限（天）" width="150" align="center" prop="validityDays" />
      <el-table-column label="发放数量（张）" width="150" align="center" prop="totalNum" />
      <el-table-column label="发放状态" width="150" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['activity:activity:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['activity:activity:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改优惠卷管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="满额限制" prop="discountAmount">
          <el-input v-model="form.discountAmount" placeholder="请输入满额限制" />
        </el-form-item>
        <el-form-item label="折扣金额" prop="discountRate">
          <el-input v-model="form.discountRate" placeholder="请输入折扣金额" />
        </el-form-item>
        <el-form-item label="使用范围" prop="scopeUse">
          <el-input v-model="form.scopeUse" placeholder="请输入使用范围" />
        </el-form-item>
        <el-form-item label="适用对象" prop="applicableObjects">
          <el-input v-model="form.applicableObjects" placeholder="请输入适用对象" />
        </el-form-item>
        <el-form-item label="发放时间" prop="distributeStartTime">
          <el-date-picker clearable v-model="form.distributeStartTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择发放时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="distributeEndTime">
          <el-date-picker clearable v-model="form.distributeEndTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用期限" prop="validityDays">
          <el-input v-model="form.validityDays" placeholder="请输入使用期限" />
        </el-form-item>
        <el-form-item label="发放数量" prop="totalNum">
          <el-input v-model="form.totalNum" placeholder="请输入发放数量" />
        </el-form-item>
        <el-form-item label="库存" prop="stockNum">
          <el-input v-model="form.stockNum" placeholder="请输入库存" />
        </el-form-item>

        <el-form-item label="优惠券" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择优惠券类型" clearable>
            <el-option v-for="item in couponTypeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发放状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择发放状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addActivity,
  delActivity,
  getActivity,
  listActivity,
  updateActivity,
} from "@/api/activity/activity";

export default {
  name: "Activity",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedCouponType: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠卷管理表格数据
      activityList: [],
      // ${subTable.functionName}表格数据
      couponTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      couponTypeOptions: [], // 优惠券类型选项
      statusOptions: [
        // 发放状态选项
        { value: 0, label: "待生效" },
        { value: 1, label: "进行中" },
        { value: 2, label: "已失效" },
        { value: 3, label: "作废" },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        name: null,
        typeId: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
        ],
        typeId: [
          { required: true, message: "优惠券类型不能为空", trigger: "change" },
        ],
        discountAmount: [
          { required: true, message: "满额限制不能为空", trigger: "blur" },
        ],
        discountRate: [
          { required: true, message: "折扣金额不能为空", trigger: "blur" },
        ],
        scopeUse: [
          { required: true, message: "使用范围不能为空", trigger: "blur" },
        ],
        applicableObjects: [
          { required: true, message: "适用对象不能为空", trigger: "blur" },
        ],
        distributeStartTime: [
          { required: true, message: "发放时间不能为空", trigger: "blur" },
        ],
        distributeEndTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
        ],
        validityDays: [
          { required: true, message: "使用期限不能为空", trigger: "blur" },
        ],
        totalNum: [
          { required: true, message: "发放数量不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "发放状态不能为空", trigger: "change" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getCouponTypeOptions(); // 获取优惠券类型选项
  },
  methods: {
    /** 查询优惠卷管理列表 */
    getList() {
      this.loading = true;
      listActivity(this.queryParams).then((response) => {
        this.activityList = this.mapStatus(response.rows);
        this.activityList = this.mapCouponType(response.rows);
        this.total = response.total;
        this.loading = false;
      });
    },

    // 将数字类型的优惠券类型转换为文字描述
    mapCouponType(list) {
      return list.map((item) => {
        const typeOption = this.couponTypeOptions.find(
          (option) => option.value === item.typeId
        );
        item.typeId = typeOption ? typeOption.label : "";
        return item;
      });
    },

    // 将数字类型的发放状态转换为文字描述
    mapStatus(list) {
      return list.map((item) => {
        const statusOption = this.statusOptions.find(
          (option) => option.value === item.status
        );
        item.status = statusOption ? statusOption.label : "";
        return item;
      });
    },

    // 获取优惠券类型选项
    getCouponTypeOptions() {
      // 假设有一个 API 调用获取优惠券类型数据
      // 这里使用静态数据模拟
      this.couponTypeOptions = [
        { value: 1, label: "满减" },
        { value: 2, label: "折扣" },
      ];
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        typeId: null,
        discountAmount: null,
        discountRate: null,
        scopeUse: null,
        applicableObjects: null,
        validityDays: null,
        distributeStartTime: null,
        distributeEndTime: null,
        totalNum: null,
        stockNum: null,
        status: null,
        createTime: null,
        updateTime: null,
        isDeleted: null,
      };
      this.couponTypeList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getActivity(id).then((response) => {
        this.form = response.data;
        this.couponTypeList = response.data.couponTypeList;
        this.open = true;
        this.title = "修改优惠券管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.couponTypeList = this.couponTypeList;
          if (this.form.id != null) {
            updateActivity(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActivity(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除优惠券管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delActivity(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>